// Learn TypeScript:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/typescript.html
//  - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/reference/attributes.html
//  - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - [Chinese] http://docs.cocos.com/creator/manual/zh/scripting/life-cycle-callbacks.html
//  - [English] http://www.cocos2d-x.org/docs/creator/manual/en/scripting/life-cycle-callbacks.html

import {globalConfig} from "../config/globalConfig";
import {model} from "../web/model/Model";
import SwimShopItem from "./swimShopItem";
import HeadShopItem from "./headShopItem";
import {HeadShopData} from "../web/model/HeadModel";
import {SwimShopData} from "../web/model/SwimModel";
import Global = NodeJS.Global;
import {GlobalObject} from "../game/GameVar";
import {COMMON_CID} from "../web/model/UserModel";
import {utils} from "../utils/utils";
import GainBoard from "./gainBoard";
import ConfirmConsume from "./confirmConsume";
import executionOrder = cc._decorator.executionOrder;
import {apiUtils} from "../web/api/ApiUtils";
import ShopItem from "./shopItem";
import ShowBoard from "./showBoard";

const {ccclass, property} = cc._decorator;

@ccclass
@executionOrder(1)
export default class Shop extends cc.Component {

  @property(cc.Prefab)
  itemPrefab: cc.Prefab = null;

  @property(cc.Toggle)
  toggle1: cc.Toggle = null;

  @property(cc.Toggle)
  toggle2: cc.Toggle = null;

  @property(cc.Node)
  private confirm: cc.Node = null;

  @property(cc.Label)
  private labelCoin: cc.Label = null;

  @property(cc.Label)
  private labelDiamond: cc.Label = null;

  @property(cc.Prefab)
  private gainBoardPrefab: cc.Prefab = null;

  @property(cc.Node)
  private items: cc.Node = null;

  @property(cc.Node)
  private coinNode: cc.Node = null

  @property(cc.Node)
  private piecesNode: cc.Node = null

  @property(cc.Label)
  private piecesLabel: cc.Label = null

  @property(cc.Node)
  private consumeConfirmNode: cc.Node = null

  @property(ShowBoard)
  private showBoard: ShowBoard = null;

  private swimsData: Array<SwimShopData> = [];
  private headsData: Array<HeadShopData> = [];

  private swimNodes: Map<number, cc.Node> = new Map<number, cc.Node>()
  private headNodes: Map<number, cc.Node> = new Map<number, cc.Node>()

  private currentSelect: ShopItem = null;

  onLoad() {
    this.toggle1.node.on('toggle', this.onToggle, this);
    this.toggle2.node.on('toggle', this.onToggle, this);
    GlobalObject.confirm = this.confirm;
    this.initSwimData();
    this.initHeadData();

    this.coinChange();
    this.diamondChange();
    this.pieceChange()

    model.user.on(COMMON_CID.COIN + '', this.coinChange, this)
    model.user.on(COMMON_CID.DIAMOND + '', this.diamondChange, this)
    model.user.on(COMMON_CID.PIECE_POWERFUL + '', this.pieceChange, this)
    this.consumeConfirmNode.active = false
    this.consumeConfirmNode.on('swim-merge', this.onSwimMerge.bind(this))

    this.showBoard.node.on('powerful-merge', this.onPowerfulMerge, this)
    this.showBoard.node.on('swim-merge', this.onSwimMerge, this)
    this.showBoard.node.on('item-used', this.onItemUsed, this)
    this.onToggle({target: this.toggle1.node});
  }

  private pieceChange() {
    this.piecesLabel.string = model.user.getItemNum(COMMON_CID.PIECE_POWERFUL) + ''
  }

  private coinChange() {
    this.labelCoin.string = model.user.getItemNum(COMMON_CID.COIN) + ''
  }

  private diamondChange() {
    this.labelDiamond.string = model.user.getItemNum(COMMON_CID.DIAMOND) + ''
  }

  getGainBoard() {
    return cc.instantiate(this.gainBoardPrefab);
  }

  private onToggle(event) {
    this.items.removeAllChildren();
    switch (event.target) {
      case this.toggle1.node:
        this.onSwimToggle();
        break;
      case this.toggle2.node:
        this.onMiToggle();
        break;
    }
  }

  onSwimToggle() {
    this.headNodes.clear();
    this.swimsData.forEach(value => {
      const swim = cc.instantiate(this.itemPrefab);
      swim.on(cc.Node.EventType.TOUCH_START, this.onSelected, this)

      this.swimNodes.set(value.id, swim);
      setTimeout(() => {
        swim.getComponent(ShopItem).setData(value);
        if (value.id === model.user.activeSwim) {
          this.onSelected({target: swim})
        }
      })
      swim.parent = this.items;
    })
  }

  onMiToggle() {
    this.swimNodes.clear();
    this.headsData.forEach(value => {
      const head = cc.instantiate(this.itemPrefab)
      head.on(cc.Node.EventType.TOUCH_START, this.onSelected, this)
      setTimeout(() => {
        head.getComponent(ShopItem).setData(value);
      })
      this.headNodes.set(value.id, head)
      // head.getComponent(HeadShopItem).data = value;
      // head.on('head-change', this.onHeadChange.bind(this))
      head.parent = this.items;
    })
  }

  onSelected(e) {
    if (this.currentSelect && this.currentSelect.node === e.target) {
      return;
    }
    if (this.currentSelect) {
      this.currentSelect.selected = false;
    }
    this.currentSelect = e.target.getComponent(ShopItem);
    this.currentSelect.selected = true;
    this.showBoard.setCurrentSelect(this.currentSelect.getData())
  }

  private initSwimData() {
    this.swimsData = model.swim.shopSwimData.map(item => {
      //正在使用
      item.state = utils.getSwimState(item);
      return Object.assign(item, model.user.itemsMap[item.id])
    });
    this.swimsData.sort((a, b) => {
      return b.sortScore - a.sortScore;
    })
  }

  private initHeadData() {
    this.headsData = []
    for (let i = 0; i < model.head.shopHeadData.length; i++) {
      const item = model.head.shopHeadData[i];
      // item.state = utils.getHeadState(item);
      this.headsData.push(item)
    }
  }

  onSwimMerge(swimId: any) {
    apiUtils.mergeItem(swimId);
    GlobalObject.voiceSource.playCompose();
    model.commonResult.once('0', () => {
      this.showBoard.state = 1;
      this.onSwimGet(swimId)
    })
  }

  onSwimGet(swimId: number) {
    const gainBoard = this.getGainBoard();
    gainBoard.getComponent(GainBoard).setData(swimId);
    gainBoard.parent = this.node;
  }

  onPowerfulMerge(data: SwimShopData) {
    this.consumeConfirmNode.getComponent(ConfirmConsume).setMergeData(data)
    this.consumeConfirmNode.active = true
  }

  private onItemUsed() {
    this.swimNodes.forEach(node => {
      node.getComponent(ShopItem).refreshUsed();
    })
    this.headNodes.forEach(node => {
      node.getComponent(ShopItem).refreshUsed();
    })
  }

  onBack() {
    cc.director.loadScene('menu');
  }

}
